package OptimalAlgorithm.Linkedlist;
//https://leetcode.cn/problems/add-two-numbers/description/

public class AddTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode newHead = new ListNode();
        ListNode head = newHead;
        ListNode cur1 = l1;
        ListNode cur2 = l2;
        int value = 0;
        while (cur1 != null || cur2 != null) {
            if(cur1 != null && cur2 != null){
                value = value + cur1.val + cur2.val;
                int temp = value % 10;
                head.next = new ListNode(temp);
                head = head.next;
                value /= 10;
                cur1 = cur1.next;
                cur2 = cur2.next;
            }else if(cur1 == null){
                value = value + cur2.val;
                int temp = value % 10;
                head.next = new ListNode(temp);
                head = head.next;
                value /= 10;
                cur2 = cur2.next;
            }else {
                value = value + cur1.val;
                int temp = value % 10;
                head.next = new ListNode(temp);
                head = head.next;
                value /= 10;
                cur1 = cur1.next;
            }
        }
        if(value != 0){
            head.next = new ListNode(value);
        }
        return newHead.next;
    }
}
